var passport = require('passport');
var thenjs = require('thenjs');
var _ = require("underscore");
var models = require('../models');
var User = require('../controllers/user');
var Common = require('../util/common')

exports.apiAuthLocal = (function(){
    return passport.authenticate('local', { session: false });
})();

exports.apiAuthBearer = (function(){
    return passport.authenticate('bearer', { session: false });
})();

exports.auth = function (group) {
  if (!Common.isDefined(group)) {
    group = "normal";
  }

  return function (req, res, next) {
    var sess;
    sess = req.signedCookies.sess;
    // console.log(req.signedCookies)
    // console.log(req.cookies);

    return thenjs(function (cont) {
      if (_.isEmpty(sess)) {
        return cont(null, null);
      }
      return models.User.findOne({
        sess: sess
      }).exec(function (err, u) {
        return cont(err, u);
      });
    }).then(function (cont, u) {
      if (u) {
        u.lastActivity = Date.now();

        return u.save(function (err, u) {
          return cont(err, u);
        });
      } else {
        return cont(null, u);
      }
    }).then(function (cont, u) {
      var _ref;
      if (group) {
        if (!u) {
          next('403 没有权限');
          return;
        }
      }
      if (group && (!u.group || ((_ref = u.group) !== group && _ref !== 'admin'))) {
        return next(new Error(403));
      }
      if (!u) {
        // u = {
        //   name: "游客",
        //   group: "guest"
        // };
      } else {
        res.locals.u = req.u = User.dry(u);
      }
      return next();
    }).fail(function (cont, err) {
      return next(err);
    });
  };
};


exports.authAdmin = function (group) {
  if (!Common.isDefined(group)) {
    group = ["normal"];
  }

  return function (req, res, next) {
    if (!Array.isArray(group)) {
        next('输入类型不匹配');
        return;
    }

    var sess;
    sess = req.signedCookies.sess;
    return thenjs(function (cont) {
      if (_.isEmpty(sess)) {
        return cont(null, null);
      }

      return models.User.findOne({
        sess: sess
      }).exec(function (err, u) {
        return cont(err, u);
      });
    }).then(function (cont, u) {
      if (u) {
        u.lastActivity = Date.now();

        return u.save(function (err, u) {
          return cont(err, u);
        });
      } else {
        return cont(null, u);
      }
    }).then(function (cont, u) {
      var _ref;
      if (group) {
        if (!u) {
          next('403 没有权限');
          return;
        }
      }

      if (group && (!u.group || ((_ref = u.group) !== group && (_ref !== 'admin')))) {
        return next(new Error(403));
      }
      if (!u) {
        // u = {
        //   name: "游客",
        //   group: "guest"
        // };
      } else {
        res.locals.u = req.u = User.dry(u);
      }
      return next();
    }).fail(function (cont, err) {
      return next(err);
    });
  };
};